package com.firefly.app.biz.yhc.service;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.firefly.app.biz.yhc.dto.RequestDTO;
import com.firefly.app.biz.yhc.dto.ResponseDTO;
import com.firefly.app.biz.yhc.dto.SetupUserInfoRequest;
import com.firefly.app.biz.yhc.dto.UserChangePwdRequest;
import com.firefly.app.biz.yhc.dto.UserFindPwdRequest;
import com.firefly.app.biz.yhc.dto.UserLoginRequest;
import com.firefly.app.biz.yhc.dto.UserLogoutRequest;
import com.firefly.app.biz.yhc.dto.UserRegRequest;
import com.firefly.mobile.app.config.Config;
import com.firefly.mobile.app.context.SytApplication;
import com.firefly.mobile.app.util.HttpUtil;
import com.firefly.mobile.app.util.Md5;
import com.firefly.mobile.app.util.StringUtils;
import com.firefly.mobile.app.util.SytLog;
import com.umeng.analytics.MobclickAgent;

public class YHCServiceImpl implements YHCService{

	
	String url =Config.getString("yhc.proxy.url");
	String key =Config.getString("yhc.proxy.key");
	String desKey = Config.getString("sytuser.proxy.desKey");
	String appid = "app";
	String userUrl = Config.getString("yhc.proxy.userUrl");
	String userKey = Config.getString("yhc.proxy.userKey");
	String serviceNameContain = "sendCheckNo_userLogin_setupUserInfo_userLogout";
	
	private RequestDTO creatHeader(String serviceName,String pageNum,String pageSize,String sessionId){
		String version =  "1.0";
		String signType =  "MD5";
		RequestDTO requestDTO = new RequestDTO();
		requestDTO.setServiceName(serviceName);
		requestDTO.setSignType(signType);
		requestDTO.setVersion(version);
		requestDTO.setPageNum(pageNum);
		requestDTO.setPageSize(pageSize);
		requestDTO.setSessionId(sessionId);
		return requestDTO;
	}

	public static long lastLoginTime = 0L;
	public static String sessionId = "";
	
	private String getEnPwd(String pwd) throws UnsupportedEncodingException, Exception {
//		String enPwd = AXLoginUtil.encrypt(pwd, desKey);
		String enPwd = Md5.md5(pwd+desKey);
		return enPwd;
	}
	
	
	private String getIsEmpty(String source){
		return source==null?"":source;
	}
	
	private ResponseDTO sendToServer(RequestDTO requestDTO,String key,String url){
		// 访问参数
		Map<String, String> params = new HashMap<String, String>();
		/**通用**/
		params.put("appid", appid);
		params.put("serviceName",requestDTO.getServiceName());
		params.put("version", requestDTO.getVersion());
		params.put("signType", requestDTO.getSignType());
		params.put("pageNum", requestDTO.getPageNum());
		params.put("pageSize", requestDTO.getPageSize());
//		requestDTO.setSessionId(sessionId);
		params.put("sessionId", requestDTO.getSessionId());
		
		/**业务json参数**/
		params.put("body", requestDTO.getBody());

		ResponseDTO orderResultDTO = new ResponseDTO();
		String signSource = appid + getIsEmpty(requestDTO.getServiceName())+ getIsEmpty(requestDTO.getVersion())+ getIsEmpty(requestDTO.getSessionId()) + getIsEmpty(requestDTO.getBody()) + key;
		SytLog.i("signSource="+signSource);
		String sign = Md5.md5(signSource);
		
		params.put("sign", sign);
		// 获得返回结果
		try {
			String result = HttpUtil.getUrlAsString(url, params);
			orderResultDTO = JSONObject.parseObject(result, ResponseDTO.class);
		} catch (Exception e) {
			e.printStackTrace();
			SytLog.e("调用异常", e.toString());
		}
		return orderResultDTO;
	}

//	@Override
//	public ResponseDTO userExt(UserExtRequest userExtRequest) {
//		RequestDTO requestDTO = creatHeader("userExt", null, null, null);
//		requestDTO.setBody(JSON.toJSONString(userExtRequest));
//		return sendToServer(requestDTO);
//	}


	@Override
	public ResponseDTO biz(String serviceName,String headerInfo, String bodyInfo) {
		
		RequestDTO header = new RequestDTO();
		String encryptInfo = bodyInfo;
		String tempKey,tempUrl;
		try {
			header = JSON.parseObject(headerInfo, RequestDTO.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(serviceName.equals("userLogin")){
			UserLoginRequest userLoginRequest = JSON.parseObject(bodyInfo, UserLoginRequest.class);
			String pwd ="";
			try {
				pwd = getEnPwd(userLoginRequest.getPassword());
			}  catch (Exception e) {
				e.printStackTrace();
			}
			if (!"true".equals(userLoginRequest.getAuto())) {
				userLoginRequest.setPassword(pwd);
			}
			encryptInfo = com.alibaba.fastjson.JSONObject.toJSONString(userLoginRequest);
		}else if(serviceName.equals("getPassword")){
			UserFindPwdRequest userFindPwdRequest = JSON.parseObject(bodyInfo,UserFindPwdRequest.class);
			String newPassword ="";
			try {
				newPassword = getEnPwd(userFindPwdRequest.getNewPassword());
			}  catch (Exception e) {
				e.printStackTrace();
			}
			userFindPwdRequest.setNewPassword(newPassword);
			encryptInfo = com.alibaba.fastjson.JSONObject.toJSONString(userFindPwdRequest);
		}else if(serviceName.equals("changePwd")){
			UserChangePwdRequest userChangePwdRequest = JSON.parseObject(bodyInfo, UserChangePwdRequest.class);
			String oldpwd ="";
			String newpwd ="";
			try {
				oldpwd = getEnPwd(userChangePwdRequest.getOldPassword());
				newpwd = getEnPwd(userChangePwdRequest.getNewPassword());
			}  catch (Exception e) {
				e.printStackTrace();
			}
			userChangePwdRequest.setOldPassword(oldpwd);
			userChangePwdRequest.setNewPassword(newpwd);
			encryptInfo = com.alibaba.fastjson.JSONObject.toJSONString(userChangePwdRequest);
		}else if(serviceName.equals("userReg")){
			UserRegRequest userRegRequest = JSON.parseObject(bodyInfo, UserRegRequest.class);
			String pwd ="";
			try {
				pwd = getEnPwd(userRegRequest.getPassword());
			}  catch (Exception e) {
				e.printStackTrace();
			}
			userRegRequest.setPassword(pwd);
			encryptInfo = com.alibaba.fastjson.JSONObject.toJSONString(userRegRequest);
		}else if(serviceName.equals("setupUserInfo")){
			SetupUserInfoRequest userRegRequest = JSON.parseObject(bodyInfo, SetupUserInfoRequest.class);
			if (StringUtils.isNotEmpty(userRegRequest.getNewPwd())) {
				try {
					String newPwd = getEnPwd(userRegRequest.getNewPwd());
					userRegRequest.setNewPwd(newPwd);
				}  catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (StringUtils.isNotEmpty(userRegRequest.getOldPwd())) {
				try {
					String oldPwd = getEnPwd(userRegRequest.getOldPwd());
					userRegRequest.setOldPwd(oldPwd);
				}  catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			encryptInfo = com.alibaba.fastjson.JSONObject.toJSONString(userRegRequest);
		}
		
		RequestDTO request = creatHeader(serviceName, header.getPageNum(), header.getPageSize(), header.getSessionId());
		request.setBody(encryptInfo);
		if(serviceNameContain.contains(serviceName)){
			tempKey = userKey;
			tempUrl = userUrl;
		}else{
			tempKey = key;
			tempUrl = url;
		}
		
		ResponseDTO responseDTO = sendToServer(request,tempKey,tempUrl);
		if ("autoLogin".equals(serviceName)) {
			if ("T".equals(responseDTO.getIsSuccess())) {
				UserLoginRequest userLoginRequest = JSON.parseObject(responseDTO.getBody(), UserLoginRequest.class);
				//友盟记录登录账号活跃度（自有账号登录）
				MobclickAgent.onProfileSignIn(userLoginRequest.getMobileNo());
				/*****注册阿里云推送账户名*****/
			    CloudPushService pushService = PushServiceFactory.getCloudPushService();
			    pushService.bindAccount(userLoginRequest.getMobileNo(), new CommonCallback() {
					
					@Override
					public void onSuccess(String s) {
						SytLog.i("阿里云注册账户名成功，"+s);
					}
					
					@Override
					public void onFailed(String s, String s1) {
					}
				});
			}
		}else if("userLogin".equals(serviceName)){
			if ("T".equals(responseDTO.getIsSuccess())) {
				//友盟记录登录账号活跃度（自有账号登录）
				UserLoginRequest userLoginRequest = JSON.parseObject(bodyInfo, UserLoginRequest.class);
				MobclickAgent.onProfileSignIn(userLoginRequest.getMobileNo());
				//当用户使用第三方账号（如新浪微博）登录时，可以这样统计：
//				MobclickAgent.onProfileSignIn("WB","userID");
				/*****注册阿里云推送账户名*****/
			    CloudPushService pushService = PushServiceFactory.getCloudPushService();
			    pushService.bindAccount(userLoginRequest.getMobileNo(), new CommonCallback() {
					
					@Override
					public void onSuccess(String s) {
						SytLog.i("阿里云注册账户名成功，"+s);
					}
					
					@Override
					public void onFailed(String s, String s1) {
					}
				});
				lastLoginTime = System.currentTimeMillis();
				sessionId = responseDTO.getSessionId();
				SytApplication.WriteSharedPreferences(userLoginRequest.getMobileNo(), userLoginRequest.getPassword());
//				FireflyMobileActivity.sendMsgToSytActivity("jsExec|checkLoginCacheData("+JSON.toJSONString(responseDTO)+")");
			}
		}else if(serviceName.equals("userLogout")){
			if ("T".equals(responseDTO.getIsSuccess())) {
				UserLogoutRequest userLogoutRequest = JSON.parseObject(bodyInfo, UserLogoutRequest.class);
				//友盟账号登出统计
				MobclickAgent.onProfileSignOff();
				
				lastLoginTime = 0L;
				SytApplication.WriteSharedPreferences("", "");
				sessionId = "";
			}
		}
		
		return responseDTO;
	}


	/**发送验证码**/
//	@Override
//	public ResponseDTO sendValidCode(UserValidCodeRequest userValidCodeRequest) {
//		/**通用**/
//		RequestDTO requestDTO = creatHeader("sendCheckNo", null, null, null);
//		requestDTO.setBody(JSON.toJSONString(userValidCodeRequest));
//		return sendToServer(requestDTO);
//	}


	@Override
	public ResponseDTO autoLogin() {
//		SytLog.i("开始自动登陆");
//		UserLoginRequest userLoginRequest = SytApplication.ReadSharedPreferences();
//		//如果已经记录了用户名和密码，自动登陆
//		if (StringUtils.isNotEmpty(userLoginRequest.getMobileNo()) && StringUtils.isNotEmpty(userLoginRequest.getPassword())) {
//			userLoginRequest.setAuto("true");
//			return userLogin(userLoginRequest);
//		}
		return null;
	}

}
